import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { message, Popconfirm, Table } from 'antd';

class AlarmDetail extends Component {

  constructor(props) {
    super(props);
    this.columns = [{
      title: 'UUID',
      dataIndex: 'uuid',
      key: 'uuid',
      width: '19%',
    }, {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: '11%',
    }, {
      title: '告警源',
      dataIndex: 'source',
      key: 'source',
      width: '11%',
    }, {
      title: '告警信息',
      dataIndex: 'msgText',
      key: 'msgText',
      width: '17%',
    }, {
      title: '告警源状态',
      dataIndex: 'sourceState',
      key: 'sourceState',
      width: '11%',
    }, {
      title: '告警分类',
      dataIndex: 'alarmClass',
      key: 'alarmClass',
      width: '11%',
    }, {
      title: '响应时间',
      dataIndex: 'ackTime',
      key: 'ackTime',
      width: '11%',
    }, {
      title: '操作',
      render: (record) => {
        return (
          <span>
            <Popconfirm title='确认该告警吗？' onConfirm={() => this.ackEachAlarm(record.uuid)}>
              <a>Confirm</a>
            </Popconfirm>
          </span>
        )
      },
      width: '9%',
    }];
  }

  handlePageChange = (changePageNo) => {
    const { pageNo, dispatch } = this.props;
    if (changePageNo !== pageNo) {
      dispatch({ type: 'alarmDetail/fetch', payload: { pageNo: changePageNo } });
    }
  };

  ackEachAlarm = (uuid) => {
    this.props.dispatch({
      type: 'alarmDetail/ackEachAlarm',
      payload: uuid,
    }).then(response => {
      if (response && typeof response.state !== undefined && response.state === 0) {
        message.success(response.message || '确认成功');
        this.reload();
      } else {
        message.error('确认失败');
      }
    });
  }

  reload = ()=> {
    this.props.dispatch({type: 'alarmDetail/fetch', payload:{ ord: this.props.alarmOrd, pageNo: 1}});
  }

  componentDidMount() {
    this.reload();
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.alarmOrd !== this.props.alarmOrd) {
      this.props.alarmOrd = nextProps.alarmOrd;
      this.props.dispatch({type: 'alarmDetail/fetch', payload:{ ord: this.props.alarmOrd, pageNo: 1}});
    }
  }

  render() {
    const { list, total, pageNo, pageSize, loading } = this.props;
    return (
      <Table
        className={'table-wrapper'}
        columns={this.columns}
        dataSource={list}
        rowKey='_id'
        loading={loading}
        pagination={{
          total: total,
          pageSize: pageSize,
          current: pageNo,
          onChange: this.handlePageChange,
        }}
      />
    );
  }
}

AlarmDetail.propTypes = {
  alarmOrd: PropTypes.string.isRequired
}

export default connect(({ alarmDetail, loading }) => ({
  ...alarmDetail,
  loading: loading.effects['alarmDetail/fetch'],
}))(AlarmDetail);
